<template>
  <div class="dish-edit-page">
    <div class="page-header">
      <div class="title">{{ isEdit ? '编辑菜品' : '新增菜品' }}</div>
      <div class="desc">{{ isEdit ? '修改菜品信息和口味设置' : '添加新的菜品和口味设置' }}</div>
    </div>

    <div class="content-card">
      <el-form 
        ref="dishFormRef" 
        :model="dishForm" 
        :rules="rules" 
        label-width="100px"
        class="dish-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜品名称" prop="name">
              <el-input v-model="dishForm.name" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="菜品分类" prop="categoryId">
              <el-select v-model="dishForm.categoryId" placeholder="请选择菜品分类" style="width: 100%">
                <el-option 
                  v-for="item in categoryList" 
                  :key="item.id" 
                  :label="item.name" 
                  :value="item.id" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="菜品价格" prop="price">
              <el-input-number 
                v-model="dishForm.price" 
                :min="0" 
                :max="99999" 
                :precision="2" 
                :step="1"
                style="width: 100%"
              />
              <div class="form-tip">单位：元（精确到分）</div>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="isEdit">
            <el-form-item label="菜品状态">
              <el-radio-group v-model="dishForm.status">
                <el-radio :label="1">起售</el-radio>
                <el-radio :label="0">停售</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="菜品图片" prop="image">
          <el-upload
            class="dish-uploader"
            :http-request="handleUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
            accept="image/jpeg,image/png,image/jpg,image/gif"
          >
            <img v-if="dishForm.image" :src="dishForm.image" class="dish-image" />
            <el-icon v-else class="dish-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="form-tip">建议上传图片尺寸为500×500，大小不超过2MB</div>
        </el-form-item>

        <el-form-item label="菜品描述">
          <el-input 
            v-model="dishForm.description" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入菜品描述"
          />
        </el-form-item>

        <!-- 口味设置 -->
        <el-form-item label="口味设置">
          <div class="flavors-container">
            <div class="add-flavor">
              <el-button type="primary" @click="addFlavor" plain class="flavor-btn">
                <el-icon><Plus /></el-icon>
                <span>添加口味</span>
              </el-button>
            </div>
            
            <div v-if="dishForm.flavors && dishForm.flavors.length > 0" class="flavor-list">
              <el-row v-for="(flavor, index) in dishForm.flavors" :key="index" :gutter="10" class="flavor-item">
                <el-col :span="6">
                  <el-input v-model="flavor.name" placeholder="口味名称，如辣度" />
                </el-col>
                <el-col :span="15">
                  <el-select 
                    v-model="flavor.value" 
                    multiple 
                    filterable 
                    allow-create 
                    default-first-option
                    placeholder="请输入选项，按Enter键确认" 
                    style="width: 100%"
                  >
                    <el-option
                      v-for="(option, idx) in getOptionsForFlavor(flavor.name)"
                      :key="idx"
                      :label="option"
                      :value="option"
                    />
                  </el-select>
                </el-col>
                <el-col :span="3" class="flavor-actions">
                  <el-button type="danger" @click="removeFlavor(index)" circle plain class="delete-btn">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-form-item>
      </el-form>

      <div class="form-actions">
        <el-button @click="goBack" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="submitForm" class="submit-btn">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import dishApi from '@/api/dish'
import categoryApi from '@/api/category'
import commonApi from '@/api/common'

const route = useRoute()
const router = useRouter()

// 是否为编辑模式
const isEdit = computed(() => route.params.id !== undefined)

// 表单数据
const dishFormRef = ref(null)
const dishForm = reactive({
  id: null,
  name: '',
  categoryId: null,
  price: 0,
  status: 1,
  image: '',
  description: '',
  flavors: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择菜品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入菜品价格', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传菜品图片', trigger: 'change' }
  ]
}

// 分类列表
const categoryList = ref([])

// 口味选项预设
const flavorPresets = {
  '辣度': ['不辣', '微辣', '中辣', '特辣'],
  '甜度': ['无糖', '微甜', '半糖', '全糖'],
  '温度': ['常温', '热饮', '温饮', '去冰', '少冰', '多冰'],
  '份量': ['小份', '中份', '大份'],
  '调料': ['不要葱', '不要蒜', '不要辣', '不要香菜']
}

// 获取口味预设选项
const getOptionsForFlavor = (flavorName) => {
  return flavorPresets[flavorName] || []
}

// 添加口味
const addFlavor = () => {
  dishForm.flavors.push({
    name: '',
    value: []
  })
}

// 删除口味
const removeFlavor = (index) => {
  dishForm.flavors.splice(index, 1)
}

// 获取分类列表
const getCategoryList = async () => {
  try {
    // 只获取菜品分类（type=1）
    const res = await categoryApi.getCategoryList(1)
    if (res.code === 1) {
      categoryList.value = res.data || []
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
  }
}

// 获取菜品详情
const getDishDetail = async () => {
  if (!isEdit.value) return
  
  try {
    const id = route.params.id
    const res = await dishApi.getDishById(id)
    if (res.code === 1) {
      // 处理价格
      let dishData = { ...res.data }
      
      // 处理口味数据
      if (dishData.flavors && dishData.flavors.length > 0) {
        dishData.flavors = dishData.flavors.map(flavor => {
          // 如果flavor.value是字符串，尝试解析成数组
          if (typeof flavor.value === 'string') {
            try {
              flavor.value = JSON.parse(flavor.value)
            } catch (e) {
              // 如果解析失败，将其转换为数组
              flavor.value = [flavor.value]
            }
          }
          return flavor
        })
      } else {
        dishData.flavors = []
      }
      
      // 更新表单数据
      Object.assign(dishForm, dishData)
    }
  } catch (error) {
    console.error('获取菜品详情失败:', error)
    ElMessage.error('获取菜品详情失败')
  }
}

// 图片上传前验证
const beforeUpload = (file) => {
  const isImage = /^image\/(jpeg|png|jpg|gif)$/.test(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2
  
  if (!isImage) {
    ElMessage.error('只能上传 JPG/PNG/GIF 格式的图片!')
    return false
  }
  
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  
  return true
}

// 自定义上传处理
const handleUpload = async (options) => {
  try {
    const res = await commonApi.upload(options.file)
    if (res.code === 1) {
      dishForm.image = res.data
      ElMessage.success('图片上传成功')
    }
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
}

// 提交表单
const submitForm = async () => {
  dishFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 处理价格
        const submitData = { ...dishForm }
        
        // 处理口味数据
        if (submitData.flavors && submitData.flavors.length > 0) {
          // 过滤掉没有名称或没有选项的口味
          submitData.flavors = submitData.flavors.filter(
            flavor => flavor.name && flavor.value && flavor.value.length > 0
          )
          
          // 将口味选项数组转换为JSON字符串
          submitData.flavors.forEach(flavor => {
            if (Array.isArray(flavor.value)) {
              flavor.value = JSON.stringify(flavor.value)
            }
          })
        }
        
        // 根据是否编辑模式选择API方法
        const apiMethod = isEdit.value ? dishApi.updateDish : dishApi.addDish
        const res = await apiMethod(submitData)
        
        if (res.code === 1) {
          ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
          goBack()
        }
      } catch (error) {
        console.error(isEdit.value ? '修改菜品失败:' : '添加菜品失败:', error)
        ElMessage.error(isEdit.value ? '修改菜品失败' : '添加菜品失败')
      }
    } else {
      return false
    }
  })
}

// 返回列表页
const goBack = () => {
  router.push('/dish')
}

// 生命周期
onMounted(() => {
  getCategoryList()
  getDishDetail()
})
</script>

<style scoped>
.dish-edit-page {
  background: #f9f9f9;
  min-height: calc(100vh - 50px);
  padding: 24px;
  transition: all 0.3s;
}

.page-header {
  margin-bottom: 24px;
  border-left: 4px solid #409EFF;
  padding-left: 16px;
}

.page-header .title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
  transition: all 0.3s;
}

.page-header .desc {
  font-size: 14px;
  color: #606266;
}

.content-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  padding: 30px;
  transition: all 0.3s;
}

.dish-form {
  margin: 20px 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}

.cancel-btn {
  margin-right: 12px;
  transition: all 0.3s;
}

.submit-btn {
  transition: all 0.3s;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
}

.dish-uploader {
  width: 180px;
  height: 180px;
  border: 2px dashed #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
}

.dish-uploader:hover {
  border-color: #409EFF;
  background-color: rgba(64, 158, 255, 0.05);
}

.dish-uploader-icon {
  font-size: 40px;
  color: #c0c4cc;
  width: 180px;
  height: 180px;
  line-height: 180px;
  text-align: center;
  transition: color 0.3s;
}

.dish-uploader:hover .dish-uploader-icon {
  color: #409EFF;
}

.dish-image {
  width: 180px;
  height: 180px;
  display: block;
  object-fit: cover;
  border-radius: 4px;
}

.flavors-container {
  margin-top: 10px;
}

.add-flavor {
  margin-bottom: 20px;
}

.flavor-btn {
  display: flex;
  align-items: center;
}

.flavor-btn .el-icon {
  margin-right: 4px;
}

.flavor-list {
  margin-top: 14px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  padding: 14px;
  background-color: #fcfcfc;
}

.flavor-item {
  margin-bottom: 14px;
  padding-bottom: 14px;
  display: flex;
  align-items: center;
  border-bottom: 1px dashed #f0f0f0;
}

.flavor-item:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.flavor-actions {
  display: flex;
  justify-content: center;
  align-items: center;
}

.delete-btn {
  transition: all 0.3s;
}

.delete-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.2);
}

/* 表单项增强样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px #dcdfe6;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover),
:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #c0c4cc;
}

:deep(.el-input__wrapper.is-focus),
:deep(.el-textarea__inner:focus) {
  box-shadow: 0 0 0 1px #409EFF;
}

:deep(.el-select__popper) {
  border-radius: 8px;
}

:deep(.el-radio__inner) {
  transition: all 0.3s;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .dish-edit-page {
    padding: 16px;
  }
  
  .content-card {
    padding: 20px;
  }
  
  .page-header .title {
    font-size: 20px;
  }
}
</style> 